<?php
class Analyser_Function extends AbstractAnalyser {
	private $_functioName = null;
	private $_state = null;
	private $_typeFunction = null;
	private $_parameters = array();

	protected function registerEvents() {
		$this->register('token.T_FUNCTION', 'onFunction');
		$this->register('class.enter', 'onClassEnter');
		$this->register('class.exit', 'onClassExit');
		$this->register('token.T_STRING', 'onString');
		$this->register('round_bracket.open', 'onOpenParenthesis');
		$this->register('round_bracket.close', 'onCloseParenthesis');
	}

	public function reset() {
		$this->_typeFunction = null;
		$this->_functioName = null;
		$this->_state = null;
		$this->_parameters = array();
	}

	public function onClassEnter() {
		$this->_state = 'in class';
	}

	public function onClassExit() {
		$this->_state = null;
	}

	public function onFunction(  ) {
		// Where are looking for functions, not methods
		if($this->_state === 'in class') return;
		
		$offset = 2;
		$token = $this->getToken($offset);
		if( $token[0] === T_STRING ) {
			$this->_functioName = $token[1];
			$this->_typeFunction = 'named';
			$offset++;
			if( $token[0] === T_WHITESPACE) {
				$this->send('syntax.space', 'before.parameters.parenthesis');
				$offset++;
			}
		} elseif( $token[1] === '(') {
			$this->_functioName = null;
			$this->_typeFunction = 'anonymous';
		}
		
		// parse error !?
		if( $token[1] !== '(') return;
		
		
	}

	public function onString($event, $token) {
		// We do not parse a function
		if( $this->_state === null) return;
		
		if( $this->_state === 'waiting name') {
			$this->_state = 'waiting parenthesis';
			$this->_functioName = $token[1];
			$this->_typeFunction = 'named';	
		}
	}

	public function onOpenParenthesis($event, $id) {
		// We do not parse a function
		if( $this->_state === null) return;

		if( $this->_state === 'waiting name') {
			// anonymous function
			$this->_typeFunction = 'anonymous';
			$this->_state = 'waiting parameter';
			$this->_closeParenthesis = $id;
			return;
		} elseif( $this->_state === 'waiting parenthesis') {
			$this->_state = 'waiting parameter';
			$this->_closeParenthesis = $id;
		}
	}
	
	public function onCloseParenthesis($event, $id) {
		// We do not parse a function
		if( $this->_state === null) return;
		
		if( $this->_state === 'waiting parameter') {
			if( $id === $this->_closeParenthesis ) {
				$this->_state = 'waiting open curly bracket';
				$this->send('function.parameters', $this->_parameters);
			}
		}
	}

	public function onBracket() {
		// We don't care about bracket
		if( $this->_state === null) return;


	}
}